package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.ListDO;
import com.bootdo.system.domain.ReportImgDO;
import com.bootdo.system.service.ListService;
import com.bootdo.system.service.ReportImgService;
import com.bootdo.system.vo.DeliveryDetailVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发货表
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2021-04-23 10:54:38
 */

@Controller
@RequestMapping("/system/list")
public class ListController {
    @Autowired
    private ListService listService;

    @Autowired
    private ReportImgService reportImgService;

    @Value("${bootdo.uploadPath}")
    private String uploadPath;

    @GetMapping()
    @RequiresPermissions("system:list:list")
    String List() {
        return "system/list/list";
    }

    @GetMapping("/checkImg/{id}")
    String checkImg(@PathVariable("id") String id, Model model){
        //获取质检报告图片
        ListDO listDO = listService.get(id);
        List<ReportImgDO> reportImgDOS = new ArrayList<>();
        //根据产品名称和批号和规格和有效期查询，未查询到的话根据产品名称和批号查询
        reportImgDOS = reportImgService.getImgInfo(listDO.getProductName(), listDO.getBatchNumber(), "", listDO.getProductGuige(), listDO.getValidDate());
        if(reportImgDOS.isEmpty()){
            reportImgDOS = reportImgService.getImgInfo(listDO.getProductName(), listDO.getBatchNumber(), "", "", "");
        }
        JSONArray json = JSONArray.fromObject(reportImgDOS);
        model.addAttribute("reportImgDOS", json);
        return "system/list/checkImg";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:list:list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        String productPositionNumber = (String) params.get("productPositionNumber");
        if(StringUtils.isNotBlank(productPositionNumber)){
            String[] productPositionNumberArr = productPositionNumber.split(",");
            params.put("productPositionNumbers", productPositionNumberArr);
        }
        Query query = new Query(params);
        List<DeliveryDetailVO> listList = listService.list(query);
        int total = listService.count(query);
        PageUtils pageUtils = new PageUtils(listList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("system:list:add")
    String add() {
        return "system/list/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:list:edit")
    String edit(@PathVariable("id") String id, Model model) {
        ListDO list = listService.get(id);
        model.addAttribute("list", list);
        return "system/list/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:list:add")
    public R save(ListDO list) {
        if (listService.save(list) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:list:edit")
    public R update(ListDO list) {
        listService.update(list);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:list:remove")
    public R remove(String id) {
        if (listService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:list:batchRemove")
    public R remove(@RequestParam("ids[]") String[] ids) {
        listService.batchRemove(ids);
        return R.ok();
    }

    @Log("导入")
    @PostMapping(value = "/import")
    @ResponseBody
    public R importInfo(@RequestParam("file") MultipartFile file, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            listService.importInfo(file, ShiroUtils.getUser().getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Model model) {
        DeliveryDetailVO deliveryDetailVO = listService.detail(id);
        model.addAttribute("info", deliveryDetailVO);

        //根据产品名称和批号和规格和有效期查询，未查询到的话根据产品名称和批号查询
        List<ReportImgDO> reportImgDOS = new ArrayList<>();
        reportImgDOS = reportImgService.getImgInfo(deliveryDetailVO.getProductName(),
                deliveryDetailVO.getBatchNumber(), "", deliveryDetailVO.getProductGuige(), deliveryDetailVO.getValidDate());
        if(reportImgDOS.isEmpty()){
            reportImgDOS = reportImgService.getImgInfo(deliveryDetailVO.getProductName(),
                    deliveryDetailVO.getBatchNumber(), "", "", "");
        }
        if(!reportImgDOS.isEmpty()){
            deliveryDetailVO.setImgUrls(reportImgDOS);
        }
        JSONArray json = JSONArray.fromObject(reportImgDOS);
        model.addAttribute("reportImgDOS", json);
        return "system/list/detail";
    }

    /**
     * 打印
     */
    @RequestMapping({"/print"})
    public void showPdf(@RequestParam("imgUrl") String[] imgUrl, HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintToPdfUtil.toPdf(imgUrl, uploadPath, uploadPath + "a_print.pdf");
            FileInputStream fis = new FileInputStream("C:/inspectionReport/a_print.pdf");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fis), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/updatePrintNum"})
    @ResponseBody
    public void updatePrintNum(@RequestParam("ids[]") String[] ids) {
        listService.updatePrintNum(ids);
    }



}
